//
//  DCFOpenWebUrlViewController.m
//  DCF
//
//  Created by 吴文拼 on 2017/12/26.
//  Copyright © 2017年 吴文拼. All rights reserved.
//

#import "DCFHomeWebUrlViewController.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JSContext.h>
#import <MediaPlayer/MediaPlayer.h>
#import "DCFNetworkManager.h"
#import "NSDate+Category.h"
#import "UIView+DCFToast.h"
#import "ServerAPISetting.h"
#import "DCFUserInfoView.h"
#import "DCFLoginHomeViewController.h"
#import "DCFLoginManager.h"
#import "DCFOpenWebUrlViewController.h"
#import "DCFCommonUtils.h"
#import <YWFeedbackFMWK/YWFeedbackKit.h>

typedef enum{
    loadWebURLString = 0,
    loadWebHTMLString,
    POSTWebURLString,
}wkWebLoadType;

static void *WkwebBrowserContext = &WkwebBrowserContext;

@interface DCFHomeWebUrlViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>

//设置加载进度条
@property (nonatomic,strong) UIProgressView *progressView;
//仅当第一次的时候加载本地JS
@property(nonatomic,assign) BOOL needLoadJSPOST;
//网页加载的类型
@property(nonatomic,assign) wkWebLoadType loadType;
//保存的网址链接
@property (nonatomic, copy) NSString *URLString;
//保存POST请求体
@property (nonatomic, copy) NSString *postData;
//保存请求链接
@property (nonatomic)NSMutableArray* snapShotsArray;


@property (nonatomic , strong)WKWebView *webView;

@property (nonatomic , strong) UIBarButtonItem *closePageBarButtonItem; //关闭h5按钮

@property (nonatomic , strong) UIBarButtonItem *backBarButtonItem; //返回按钮

@property (nonatomic , strong) UIBarButtonItem *leftBarButtonItem; //左边按钮
@property (nonatomic , strong) UIBarButtonItem *rightBarButtonItem; //右边按钮

//正在显示的url
@property (nonatomic ,   copy)NSString *currentUrl;

@property (nonatomic , strong)DCFUserInfoView *leftView;

@property (nonatomic , strong)YWFeedbackKit *feedbackKit;


@end

@implementation DCFHomeWebUrlViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    self.URLString = self.url;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.URLString]];
    [DCFNetworkManager giveHTTPRequestHeader:request];
    [self.webView loadRequest:request];
    [self.view addSubview:self.webView];
    //添加进度条
    [self.view addSubview:self.progressView];
}

- (WKWebView *)webView
{
    if (!_webView) {
        //设置网页的配置文件
        WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc]init];
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0f) {
            //允许视频播放
            Configuration.allowsAirPlayForMediaPlayback = YES;
        }
        // 允许在线播放
        Configuration.allowsInlineMediaPlayback = YES;
        // 允许可以与网页交互，选择视图
        Configuration.selectionGranularity = YES;
        // web内容处理池
        Configuration.processPool = [[WKProcessPool alloc] init];
        //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
        WKUserContentController * UserContentController = [[WKUserContentController alloc]init];
        // 添加消息处理，注意：self指代的对象需要遵守WKScriptMessageHandler协议，结束时需要移除
        [UserContentController addScriptMessageHandler:self name:@"jsToOcAction"];
        // 是否支持记忆读取
        Configuration.suppressesIncrementalRendering = YES;
        // 允许用户更改网页的设置
        Configuration.userContentController = UserContentController;
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, STATUS_NAVIGATIONBAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_NAVIGATIONBAR_HEIGHT) configuration:Configuration];
        _webView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];
        // 设置代理
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        //kvo 添加进度监控
        [_webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkwebBrowserContext];
        //开启手势触摸
        _webView.allowsBackForwardNavigationGestures = YES;
        // 设置 可以前进 和 后退
        //适应你设定的尺寸
        [_webView sizeToFit];
        
    }
    return _webView;
}


#pragma mark ================ 加载方式 ================

- (void)webViewloadURLType{
    switch (self.loadType) {
        case loadWebURLString:{
            //创建一个NSURLRequest 的对象
            //            NSURLRequest * Request_zsj = [NSURLRequest requestWithURL:[NSURL URLWithString:self.URLString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
            //加载网页
            
            [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.URLString]]];
            break;
        }
        case loadWebHTMLString:{
            [self loadHostPathURL:self.URLString];
            break;
        }
        case POSTWebURLString:{
            // JS发送POST的Flag，为真的时候会调用JS的POST方法
            self.needLoadJSPOST = YES;
            //POST使用预先加载本地JS方法的html实现，请确认WKJSPOST存在
            [self loadHostPathURL:@"WKJSPOST"];
            break;
        }
    }
}

- (void)loadHostPathURL:(NSString *)url{
    //获取JS所在的路径
    NSString *path = [[NSBundle mainBundle] pathForResource:url ofType:@"html"];
    //获得html内容
    NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //加载js
    [self.webView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
}

// 调用JS发送POST请求
- (void)postRequestWithJS {
    // 拼装成调用JavaScript的字符串
    NSString *jscript = [NSString stringWithFormat:@"post('%@',{%@});", self.URLString, self.postData];
    // 调用JS代码
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.webView evaluateJavaScript:jscript completionHandler:^(id object, NSError * _Nullable error) {
        }];
    });
}


- (void)loadWebURLSring:(NSString *)string{
    self.URLString = string;
    self.loadType = loadWebURLString;
}

- (void)loadWebHTMLSring:(NSString *)string{
    self.URLString = string;
    self.loadType = loadWebHTMLString;
}

- (void)POSTWebURLSring:(NSString *)string postData:(NSString *)postData{
    self.URLString = string;
    self.postData = postData;
    self.loadType = POSTWebURLString;
}

//请求链接处理
-(void)pushCurrentSnapshotViewWithRequest:(NSURLRequest*)request{
    NSLog(@"snapShotsArray %ld",self.snapShotsArray.count);
    NSURLRequest* lastRequest = (NSURLRequest*)[[self.snapShotsArray lastObject] objectForKey:@"request"];
    
    //如果url是很奇怪的就不push
    if ([request.URL.absoluteString isEqualToString:@"about:blank"]) {
        //        NSLog(@"about blank!! return");
        return;
    }
    //如果url一样就不进行push
    if ([lastRequest.URL.absoluteString isEqualToString:request.URL.absoluteString]) {
        return;
    }
    UIView* currentSnapShotView = [self.webView snapshotViewAfterScreenUpdates:YES];
    if (currentSnapShotView) {
        [self.snapShotsArray addObject:
         @{@"request":request,@"snapShotView":currentSnapShotView}];
    }
}

#pragma mark ================ WKNavigationDelegate ================

//这个是网页加载完成，导航的变化
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    /*
     主意：这个方法是当网页的内容全部显示（网页内的所有图片必须都正常显示）的时候调用（不是出现的时候就调用），，否则不显示，或则部分显示时这个方法就不调用。
     */
    // 判断是否需要加载（仅在第一次加载）
    if (self.needLoadJSPOST) {
        // 调用使用JS发送POST请求的方法
        [self postRequestWithJS];
        // 将Flag置为NO（后面就不需要加载了）
        self.needLoadJSPOST = NO;
    }
    // 获取加载网页的标题
    self.title = self.webView.title;
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    
    [self updateNavigationItems];
}

//开始加载
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    //开始加载的时候，让加载进度条显示
    self.progressView.hidden = NO;
    
    
    
}

//内容返回时调用
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}

//服务器请求跳转的时候调用
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}

//-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
//
//    if ([_currentUrl isEqualToString:@"http://192.168.0.45:230/zhima/callback"]) {
//        NSHTTPURLResponse *response = navigationResponse.response;
//        NSLog(@"%@",response.allHeaderFields);
//        decisionHandler(WKNavigationResponsePolicyCancel);
//        [self.navigationController popViewControllerAnimated:YES];
//    }else{
//        decisionHandler(WKNavigationResponsePolicyAllow);
//    }
//}

//服务器开始请求的时候调用
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString *currentUrl = [navigationAction.request.URL absoluteString];
    _currentUrl = currentUrl;
    if ([currentUrl containsString:@"/zhima/acreditZhima"]) {
        [DCFNetworkManager postDCFTo:currentUrl withJSON:nil successHandler:^(DCFResponseModel *response) {
            if (response.success) {
                if (_completeBlock) {
                    _completeBlock();
                }
                [[UIApplication sharedApplication].keyWindow makeCenterToastWithShowMessage:@"认证成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [[UIApplication sharedApplication].keyWindow makeCenterToastWithShowMessage:response.message];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } failHandler:^(NSError *error) {
            [[UIApplication sharedApplication].keyWindow makeCenterToastWithShowMessage:DCF_NORMAL_UNLINK_NET_TOAST];
            [self.navigationController popViewControllerAnimated:YES];
        }];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    switch (navigationAction.navigationType) {
        case WKNavigationTypeLinkActivated: {
            [self pushCurrentSnapshotViewWithRequest:navigationAction.request];
            break;
        }
        case WKNavigationTypeFormSubmitted: {
            [self pushCurrentSnapshotViewWithRequest:navigationAction.request];
            break;
        }
        case WKNavigationTypeBackForward: {
            break;
        }
        case WKNavigationTypeReload: {
            break;
        }
        case WKNavigationTypeFormResubmitted: {
            break;
        }
        case WKNavigationTypeOther: {
            [self pushCurrentSnapshotViewWithRequest:navigationAction.request];
            break;
        }
        default: {
            break;
        }
    }
    
    [self updateNavigationItems];
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 内容加载失败时候调用
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"页面加载超时");
    
}

//跳转失败的时候调用
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    [self updateNavigationItems];
}

//进度条
-(void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    NSLog(@"webview加载结束%.2f",webView.estimatedProgress);
}

#pragma mark ================ WKUIDelegate ================

// 获取js 里面的提示
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
}

// js 信息的交流
-(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

// 交互。可输入的文本。
-(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS调用输入框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor redColor];
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([[alert.textFields lastObject] text]);
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    
}

//KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.webView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.webView.estimatedProgress animated:animated];
        NSLog(@"webview加载了%.2f",self.webView.estimatedProgress);
        // Once complete, fade out UIProgressView
        if(self.webView.estimatedProgress >= 1.0f) {
            NSLog(@"webview加载结束%.2f",self.webView.estimatedProgress);
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark ================ WKScriptMessageHandler ================

//拦截执行网页中的JS方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
    //服务器固定格式写法 window.webkit.messageHandlers.名字.postMessage(内容);
    //客户端写法 message.name isEqualToString:@"名字"]
    WEAKSELF
    
    if ([message.name isEqualToString:@"jsToOcAction"]) {
        NSLog(@"%@", message.body);
        
        NSDictionary *jsDic = message.body;
        if (jsDic[@"case"]) {
            switch ([jsDic[@"case"] integerValue]) {
                case 1:
                {
                    if ([DCFLoginManager sharedInstance].isLogin) {
                        NSDictionary *data = [DCFNetworkManager getHeaderDic];
                        NSString *js = [NSString stringWithFormat:@"getPara(%@)",[DCFCommonUtils convertToJsonData:data]];
                        [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                            
                        }];
                    }else{
                        DCFLoginHomeViewController *vc = [[DCFLoginHomeViewController alloc] init];
                        [self.navigationController presentViewController:vc animated:YES completion:^{
                            
                        }];
                    }
                }
                    break;
                case 2:
                {
                    NSString *url = jsDic[@"url"];
                    DCFOpenWebUrlViewController *vc = [[DCFOpenWebUrlViewController alloc] init];
                    vc.url = url;
                    vc.backBlock = ^{
                        NSString *js = [NSString stringWithFormat:@"popup()"];
                        [weakSelf.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                            
                        }];
                    };
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case 3:
                {
                    NSDictionary *data = [DCFNetworkManager getHeaderDic];
                    NSString *js = [NSString stringWithFormat:@"getParaTwo(%@)",[DCFCommonUtils convertToJsonData:data]];
                    [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                        if (error) {
                            NSLog(@"fskljfdalkfjdslkjfdsljfjdfsljsdl");
                        }
                    }];
                }
                    break;
                case 4:
                {
                    [[DCFLoginManager sharedInstance] logoutWithCompleteBlock:^(BOOL success) {
                        
                    }];
                    [self.view makeCenterToastWithShowMessage:@"请重新登录"];
                }
                    break;
                    
                default:
                    break;
            }
        }
        
        
        JSValue *this = [JSContext currentThis];
        NSLog(@"this: %@",this);
    }
}

#pragma mark ---- 进度条 ------
- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.frame = CGRectMake(0, STATUS_NAVIGATIONBAR_HEIGHT, self.view.bounds.size.width, 3);
        
        // 设置进度条的色彩
        [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
        _progressView.progressTintColor = [UIColor greenColor];
    }
    return _progressView;
}

#pragma mark ================ 自定义返回/关闭按钮 ================

-(void)updateNavigationItems{
    self.title = self.webView.title;
    if (self.webView.canGoBack) {
        [self.navigationItem setLeftBarButtonItems:@[self.backBarButtonItem] animated:NO];
//        self.navigationItem.rightBarButtonItem = nil;
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
        self.navigationController.navigationBar.tintColor = kMainColor;
    }else{
        [self.navigationItem setLeftBarButtonItems:@[self.leftBarButtonItem]];
//        self.navigationItem.rightBarButtonItem = self.rightBarButtonItem;
        self.navigationController.navigationBar.barTintColor = RGBCOLOR(48, 130, 253);
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    }
}

- (UIBarButtonItem *)closePageBarButtonItem
{
    if (!_closePageBarButtonItem) {
        _closePageBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"  关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closePageAction)];
        _closePageBarButtonItem.tintColor = kMainColor;
    }
    return _closePageBarButtonItem;
}

- (UIBarButtonItem *)backBarButtonItem
{
    if (!_backBarButtonItem) {
        _backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back_arrow_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonPressed)];
    }
    
    return _backBarButtonItem;
}

- (UIBarButtonItem *)leftBarButtonItem
{
    if (!_leftBarButtonItem) {
        _leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"my_info_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonPressed)];
    }
    
    return _leftBarButtonItem;
}

- (UIBarButtonItem *)rightBarButtonItem
{
    if (!_rightBarButtonItem) {
        _rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"msg_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonPressed)];
    }
    
    return _rightBarButtonItem;
}

#pragma mark ---- 返回模块 ----

-(void)closePageAction{
    if (_backBlock) {
        _backBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)backBarButtonPressed{
//    if ([self.webView canGoBack]) {
//        [self.webView goBack];
//    }else{
//        if (_backBlock) {
//            _backBlock();
//        }
//        [self.navigationController popViewControllerAnimated:YES];
//    }
    [self.webView goBack];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self updateNavigationItems];
    });
}

-(void)leftBarButtonPressed{
    if ([DCFLoginManager sharedInstance].isLogin) {
        [self.leftView show];
    }else{
        DCFLoginHomeViewController *vc = [[DCFLoginHomeViewController alloc] init];
        [self.navigationController presentViewController:vc animated:YES completion:^{
            
        }];
    }
}

-(void)rightBarButtonPressed{
    if ([DCFLoginManager sharedInstance].isLogin) {
        
    }else{
        DCFLoginHomeViewController *vc = [[DCFLoginHomeViewController alloc] init];
        [self.navigationController presentViewController:vc animated:YES completion:^{
            
        }];
    }
}

-(DCFUserInfoView *)leftView{
    if (!_leftView) {
        _leftView = [[DCFUserInfoView alloc] init];
        WEAKSELF
        _leftView.feedbackBlock = ^{
            [[UIApplication sharedApplication].keyWindow makeCenterToastWithShowMessage:@"暂未开放"];
//            [weakSelf openFeedbackViewController];
        };
    }
    return _leftView;
}

-(NSMutableArray*)snapShotsArray{
    if (!_snapShotsArray) {
        _snapShotsArray = [NSMutableArray array];
    }
    return _snapShotsArray;
}

#pragma mark ---- 意见反馈 ----
//反馈建议
- (YWFeedbackKit *)feedbackKit {
    if (!_feedbackKit) {
        _feedbackKit = [[YWFeedbackKit alloc] initWithAppKey:kYWFeedBackAppKey appSecret:kYWFeedBackAppSecret];
    }
    return _feedbackKit;
}

/** 打开用户反馈页面 */
- (void)openFeedbackViewController {
    WEAKSELF
    [self.feedbackKit makeFeedbackViewControllerWithCompletionBlock:^(YWFeedbackViewController *viewController, NSError *error) {
        if (viewController != nil) {
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:viewController];
            [weakSelf.navigationController presentViewController:nav animated:YES completion:nil];
            
            [viewController setCloseBlock:^(UIViewController *aParentController){
                [aParentController dismissViewControllerAnimated:YES completion:nil];
            }];
        } else {
            [weakSelf.view makeToast:DCF_NORMAL_UNLINK_NET_TOAST duration:1.5f position:CSToastPositionCenter];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
